import { useAPIUtils } from "@/components/APIUtilsProvider";
import DictionaryItemText from "@/components/DictionaryItemText";
import PageLayout from "@/components/PageLayout";
import RenderIf from "@/components/RenderIf";
import {
  Badge,
  Box,
  Button,
  Card,
  Flex,
  Grid,
  Image,
  ScrollArea,
  Text,
  Title,
} from "@mantine/core";
import dayjs from "dayjs";
import { useState } from "react";
import { useParams } from "react-router-dom";
import ImageModal from "../../components/ImageModal";
import { moreModals } from "../../components/moreModals";
import { ProductEdit } from "./ProductEditModal";

export default function ProductDetails() {
  return (
    <PageLayout title={"商品详情"}>
      <Grid w="96%">
        <Grid.Col span={7}>
          <Basics />
        </Grid.Col>
        <Grid.Col span={3} offset={2}>
          <SideContent />
        </Grid.Col>
      </Grid>
    </PageLayout>
  );
}

const Descriptions = ({ title, data, tools }) => {
  return (
    <Box padding="md">
      <Flex justify={"space-between"} align={"baseline"}>
        <Title order={6} mb={"lg"}>
          {title}
        </Title>
        {tools}
      </Flex>

      <Grid gutter="0" style={{ border: "0.1px solid rgba(0, 0, 0, 0.1)" }}>
        {data.map((item, index) => (
          <>
            <Grid.Col
              span={2}
              bg={"gray.1"}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text weight={100} size="sm">
                {item.label}
              </Text>
            </Grid.Col>
            <Grid.Col
              span={item.block ? 10 : 4}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text>{item.value}</Text>
            </Grid.Col>
          </>
        ))}
      </Grid>
    </Box>
  );
};

function Basics() {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const [editing, setEditing] = useState(false);
  const productQuery = tanstackQuery(`/api/products/${id}`);

  if (!productQuery.data) {
    return <></>;
  }

  const product = productQuery.data;

  const descriptionsData = [
    { label: "商品名", value: product.name },

    {
      label: "状态",
      value: (
        <Badge color={product.onMarket ? "green.5" : "gray.5"} size="lg">
          {product.onMarket ? "在售" : "已下架"}
        </Badge>
      ),
    },
    {
      label: "分类",
      value: <CategoryNamesText data={product.meta.categories} />,
      block: true,
    },
    { label: "用途功效", value: product.meta.treatmentEffect, block: true },
    { label: "剩余库存", value: product.stock, block: true },
    { label: "单价", value: product.price },
    { label: "积分", value: product.pv },
    { label: "原价", value: product.meta.originalPrice, block: true },
    {
      label: "创建时间",
      value: dayjs(product.createdAt).format("YYYY/MM/DD HH:mm:ss"),
      block: true,
    },
    {
      label: "商品描述",
      value: (
        <Text style={{ whiteSpace: "pre-line" }}>{product.description}</Text>
      ),
      block: true,
    },
    {
      label: "用户反馈",
      value: <Text style={{ whiteSpace: "pre-line" }}>{product.feedback}</Text>,
      block: true,
    },
    {
      label: "权重",
      value: product.meta.weight,
      block: true,
    },
    {
      label: "详情图",
      value: (
        <ScrollArea>
          <ImageModal src={product.meta.detailImageUrl} />
        </ScrollArea>
      ),
      block: true,
    },
  ];

  const tools = (
    <Button.Group>
      <Button
        size="xs"
        variant="default"
        onClick={() =>
          window.open(`/products/${product.id}/stock/operations`, "_blank")
        }
      >
        查看库存变动
      </Button>
      <RenderIf auth="ProductRelated">
        <Button variant="default" size="xs" onClick={() => setEditing(true)}>
          修改基本信息
        </Button>
      </RenderIf>
    </Button.Group>
  );

  return (
    <>
      <ProductEdit
        source={productQuery.data}
        opened={editing}
        setOpened={setEditing}
      />
      <Descriptions
        title={`商品ID: ${id}`}
        data={descriptionsData}
        tools={tools}
      />
    </>
  );
}

function SideContent() {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const productQuery = tanstackQuery(`/api/products/${id}`);

  if (!productQuery.data) {
    return <></>;
  }

  const product = productQuery.data;

  const modifyStatus = async (action) => {
    await restPUT(`/api/admin/products/${product.id}/status?action=${action}`);
    tanstackInvalidate(`/api/admin/products`);
    tanstackInvalidate(`/api/products/${product.id}`);
  };

  const modifyStock = async (delta) => {
    await restPUT(`/api/admin/products/${product.id}/stock?delta=${delta}`);
    tanstackInvalidate(`/api/admin/products`);
    tanstackInvalidate(`/api/products/${product.id}`);
  };

  return (
    <>
      <Card shadow="sm" padding="lg" radius="md" withBorder>
        <Card.Section>
          <Image src={product.meta.imageUrl} h={400} alt="" />
        </Card.Section>
        <RenderIf auth="ProductRelated">
          <Button
            color="blue"
            fullWidth
            mt="md"
            radius="md"
            onClick={() =>
              moreModals.openPromptModal({
                title: "请输入要减少的数量",
                type: "positive-int",
                onConfirm: (v) => {
                  console.log(v, typeof v);
                  console.log(v);
                  modifyStock(-Number(v));
                },
              })
            }
          >
            减少库存
          </Button>
          <Button
            color="blue"
            fullWidth
            mt="md"
            radius="md"
            onClick={() =>
              moreModals.openPromptModal({
                title: "请输入要增加的数量",
                type: "positive-int",
                onConfirm: (v) => {
                  modifyStock(Number(v));
                },
              })
            }
          >
            增加库存
          </Button>
          {product.onMarket ? (
            <Button
              color="red"
              fullWidth
              mt="md"
              radius="md"
              onClick={() =>
                moreModals.openDefaultConfirmModal({
                  title: "确定要将该商品下架吗？",
                  onConfirm: () => {
                    modifyStatus("off");
                  },
                })
              }
            >
              下架
            </Button>
          ) : (
            <Button
              color="red"
              fullWidth
              mt="md"
              radius="md"
              onClick={() =>
                moreModals.openDefaultConfirmModal({
                  title: "确定要将该商品上架吗？",
                  onConfirm: () => {
                    modifyStatus("on");
                  },
                })
              }
            >
              上架
            </Button>
          )}
        </RenderIf>
      </Card>
    </>
  );
}

function CategoryNamesText({ data }) {
  let categories = data?.map((s) => (
    <DictionaryItemText k={s} itemKey={s} dictName="product_category" />
  ));
  return (
    <Flex gap="sm" wrap="nowrap">
      {categories}
    </Flex>
  );
}
